<?php
/*
 *  Jiba: A small collection of classes to make php easier.
 *  Copyright (C) 2007  Dimitri Michaux <dimitri.michaux@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * dbobject.class.php, Jiba
 * 
 * Every object that goes inside the database should derive from this one.
 * It generates a random id and a timestamp for your object on creation.
 *
 * @author Dimitri Michaux
 * @version 0.1
 * @package jiba
 */

require_once( 'db.class.php' );
require_once( 'timestamp.class.php' );

abstract class DBObject
{
  /**
    * Id used in the database
    *
    * @var int
    */
  protected $_id;
  
  /**
   * Timestamp
   *
   * @var Timestamp
   */
  private $_stamp;
  
  /**
   *
   *
   */
  abstract public static function save( $object );
  
  protected function __construct()
  {
    $this->_stamp = new Timestamp;
  }
  
  /**
    * Returns the internal id of the order
    *
    * @return int
    */
  public function getId() {
    return $this->_id;
  }
  
  public function getTimestamp()
  {
    return $this->_stamp;
  }
  
  /**
    * Creates a random 32 symbol id
    *
    * @return string
    */
  protected function _createId(){
    $pattern = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    if( get_class($this) == 'PurchaseOrder' )
      $key = "or"; //purchase order
    elseif( get_class($this) == 'PurchaseOffer' )
      $key = "of"; //purchase offer
    
    $key .= date("YmdHis");
    $ln = strlen($key);
    
    //chances are small this is going to be generated ever again
    for($i=0;$i<32-$ln;$i++)
        $key .= $pattern{rand(0,strlen($pattern)-1)};
    
    return $key;
  }
}

?>